<?php

/*
	Class: Commerce_Plugins_Membership

	About: Author
		Rich Joslin

	About: License
		<http://communit.as/docs/license>
*/
class Commerce_Plugins_Membership {

	/* Group: Instance Methods */

	/*
		Function: register
	*/
	function register($params) {
		$request = new Cts_Request($params['request']);
		$user = $params['user'];
		$errors = $params['errors'];
		$data = array(
			'username' => $user['username'],
			'status' => 'active',
			'first_name' => $request->first_name,
			'last_name' => $request->last_name,
			'created_on' => date(DB_DATETIME_FORMAT),
			'last_modified_on' => date(DB_DATETIME_FORMAT),
		);
		
		if( !$request->has('first_name') || empty($request->first_name) ){
			$errors[] = 'Please enter your first name.';
		} else if( !$request->has('last_name') || empty($request->last_name) ){
			$errors[] = 'Please enter your last name.';
		}
		
		$user['full_name'] = $request->first_name.' '.$request->last_name;
		$user['first_name'] = $request->first_name;
		$user['last_name'] = $request->last_name;
		
		if (count($errors) == 0) {
			// create a customer in Magento
			$magento = new CommerceMagentoMembership();
			$data['commerce_customer_id'] = $magento->createCustomer($request->first_name, $request->last_name, $user['email'], $user['password']);
			// insert a record into our site specific user table
			$commerce_users_table = new CommerceUsers();
			$userwhere = $commerce_users_table->getAdapter()->quoteInto('username = ?', $data['username']);;
			if ($commerce_users_table->getCountByWhereClause($userwhere) == 0) {
				$commerce_users_table->insert($data);
			}
		}
		$params['user'] = $user;
		$params['errors'] = $errors;
		return $params; 
	}

	/*
		Function: resetPassword
	*/
	function resetPassword($params) {
		$request = new Cts_Request($params['request']);
		$user = $params['user'];
		$errors = $params['errors'];
		$commerce_users_table = new CommerceUsers();
		$commerce_user = $commerce_users_table->findArray($user->username);
		if (count($errors) == 0) {
			$magento = new CommerceMagentoMembership();
			try {
				$magento->updateCustomerPassword($commerce_user['commerce_customer_id'], $params['password']);
			} catch (Exception $e) {
dd($e);
				$errors[] = $e->message;
			}
		}
		$params['user'] = $user;
		$params['errors'] = $errors;
		return $params; 
	}

	/*
		Function: login
	*/
	function login($params) {

		// get the session ID that was created when the Mini Cart data loaded
		$session = new Zend_Session_Namespace('Default');
		//dd( $session->magento_curl_session_id );
		$magento_curl_session_id = $session->magento_curl_session_id;
		if (is_array($magento_curl_session_id)) {
			$catalog = new CommerceMagentoCatalog();
			$customer_session_id = $magento_curl_session_id[$catalog->formatStoreId($params['locale_code'])];
		} else {
			$customer_session_id = $magento_curl_session_id;
		}

		// 1: prepare objects and data
		$username = $params['username'];
		$commerce_users_table = new CommerceUsers();
		$commerce = new CommerceMagentoMembership($customer_session_id);
		$users_table = new Users();
		$user = $users_table->fetchByUsername($username)->toArray();
		$submitted_password = $params['password'];

		// 2: set flags to be used later in conditional logic
		$whereclause = $commerce_users_table->getAdapter()->quoteInto('username = ?', $username);
		$has_commerce_user_local = (!$commerce_users_table->getCountByWhereClause($whereclause) == 0);
		$remote_customer_id = $commerce->getCustomerIdByUsername($username);
		$has_commerce_user_remote = (!is_null($remote_customer_id));

		// 3: check flags and make sure all user data is in sync between 3 systems
		// (communitas as the local source of data, a remote system as a source of data, and a local table to join the two sources)

		if (!$has_commerce_user_remote) {
			// remote user account does not exist - create it
			$remote_customer_id = $commerce->createCustomer("", "", $user['email'], $submitted_password);
			Cts_Log::report('Communitas user '.$username.' created as commerce customer_id '.$remote_customer_id, null, Zend_Log::INFO);
			$where = $commerce_users_table->getAdapter()->quoteInto('username = ?', $username);
			$commerce_users_table->update(array('commerce_customer_id' => $remote_customer_id), $where);
		}

		if (!$has_commerce_user_local) {
			// local user extension does not exist - create it
			$data = array(
				'username' => $user['username'],
				'commerce_customer_id' => $remote_customer_id,
				'status' => 'active',
				'first_name' => '',
				'last_name' => '',
				'created_on' => date(DB_DATETIME_FORMAT),
				'last_modified_on' => date(DB_DATETIME_FORMAT),
			);
			$commerce_users_table->insert($data);
		}

		// 4: log the user into the remote app
		$session_id = $commerce->loginCustomer($user['email'], $submitted_password);
		if (!is_null($session_id)) {
			Cts_Log::report('Logged user '.$user['email'].' into commerce with session id '.$session_id, null, Zend_Log::INFO);

			// TODO - MAKE THE PLUGIN HOOK PASS IN A FULL ABSOLUTE URL INSTEAD OF A VIRTUAL ONE
			// set up a URL for Magento to redirect you back to
			// if (is_null($params['requested_url'])) {
			// 	$return_url = Cts_Registry::get('remote_login_return_url_default', 'commerce');
			// } else {
			// 	$return_url = $params['requested_url'];
			// }
			
			if( array_key_exists('requested_url',$params) ){
				$url_filters = array(
					'locale_code' => $params['locale_code'],
					'absolute' => true,
				);
				$url_filter = new Cts_Url_Filter();
				$return_url = $url_filter->filter($params['requested_url'], $url_filters);
			} else {
				$return_url = Cts_Registry::get('remote_login_return_url_default', 'commerce');
			}
			
			// TODO - This is the wrong way to this, don't do it
			if( strpos($return_url, '/') !== false ){
				$return_url = base64_encode($return_url);
			}
			
			$bounce_url = Cts_Registry::get('magento_login_bounce_base_url').$return_url."?SID=".$session_id;
			Cts_Log::report('Redirecting user '.$user['email'].' to bounce URL '.$bounce_url, null, Zend_Log::INFO);
			header("Location: ".$bounce_url);
			exit;
			
			// TODO - Don't ever do this again
			$this->makeWhiteSpace();
			flush();
		} else {
			Cts_Log::report('Could not log ' . $user['email'] . ' into commerce', null, Zend_Log::INFO);
		}

	}

	/*
		Function: logout
	*/
	function logout($params) {
		header("Location: ".Cts_Registry::get('magento_logout_url'));
		$this->makeWhiteSpace();
		flush();
	}

	/* Group: Private or Protected Methods */

	/*
		Function: makeWhiteSpace
	*/
	private function makeWhiteSpace() {
		for ($x = 0; $x < 30; $x++) {
			echo("          ");
		}
	}

}
